<template>
<h1>详情页面</h1>
    <h2>{{w.nickname}}说:{{w.content}}</h2>
    <p>{{w.created}}</p>
  <hr>
  <h3>评论相关</h3>
  <el-input placeholder="说点儿啥..." v-model="c.content"></el-input>
  <el-button @click="postComment()">评论</el-button>
  <hr>
  <div v-for="comment in commentArr">
    <h4>{{comment.nickname}}评论说:{{comment.content}}</h4>
    <p style="font-size: 12px;color: #666;margin: 0">{{comment.created}}</p>
  </div>

</template>

<script setup>

import {onMounted, ref} from "vue";
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router";
import qs from "qs";

const w = ref({});
//定义评论对象
const c = ref({content:""});
const postComment = ()=>{
  //得到微博的id 和 作者id
  c.value.weiboId = w.value.id;
  //得到当前登录的用户信息
  let user = localStorage.user?JSON.parse(localStorage.user):null;
  if (user==null){
    alert("请先登录!")
    router.push('/login');
    return;
  }
  c.value.userId = user.id;//把当前登录的用户id给到评论对象
  let data = qs.stringify(c.value);//把需要传递的js对象转成查询字符串格式
  axios.post('http://localhost:8080/v1/comments/add-new',data)
      .then((response)=>{
        if (response.data.code==2001){
          ElMessage.success("评论完成!");
          //重新加载评论数据
          loadComments(w.value.id);
        }else{
          ElMessage.error(response.data.msg);
        }
      })



}
const commentArr = ref([]);
onMounted(()=>{
  //得到地址栏中的微博id
  let id = new URLSearchParams(location.search).get('id');
  console.log("id="+id);
  axios.get('http://localhost:8080/v1/weibos/'+id).then((response)=>{
    if (response.data.code==2001){
      w.value = response.data.data;
    }else{
      ElMessage.error(response.data.msg);
    }
  })
  loadComments(id);

})

const loadComments=(id)=>{
  //请求当前微博相关的评论
  axios.get('http://localhost:8080/v1/comments/'+id).then((response)=>{
    if (response.data.code==2001){
      commentArr.value = response.data.data;
    }
  })
}

</script>

<style scoped>

</style>